/**
 * Copyright 2011 Honeywell Federal Manufacturing & Technologies, LLC. This material was produced under U.S. Government
 * contract DE-ACO4-01AL66850, Honeywell Federal Manufacturing & Technologies, LLC, (FM&T) with the U. S. Department of
 * Energy for the operation of the Kansas City Plant . The U.S. Government has rights to use, reproduce, and distribute
 * this software.  NEITHER THE GOVERNMENT NOR Honeywell Federal Manufacturing & Technologies, LLC, MAKES ANY WARRANTY,
 * EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE.  If software is modified to produce
 * derivative works, such modified software should be clearly marked, so as not to confuse it with the version available
 * from FM&T.
 *
 * Additionally, this program is free software; you can redistribute it and/or modify it under the terms of the GNU
 * General Public License Version 3 published by the Free Software Foundation. Accordingly, this program is distributed in
 * the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this library.
 * If not, see http://www.gnu.org/licenses/.
 */
package org.braintrain.tapestry.view;

import com.kcp.ko.fmtnmlib.service.search.SimpleSearch;
import org.apache.tapestry.IRequestCycle;
import org.apache.tapestry.annotations.Bean;
import org.apache.tapestry.annotations.InitialValue;
import org.apache.tapestry.annotations.InjectPage;
import org.apache.tapestry.form.IFormComponent;
import org.apache.tapestry.valid.ValidationDelegate;
import org.apache.xerces.impl.xpath.regex.RegularExpression;
import org.braintrain.domain.BrainTrainProperties;
import org.braintrain.domain.types.BrainTrainProperty;

/**
 * Tapestry UserAdmin page.  This page alows the User Administrator to edit, create or delete
 * users from the BrainTrain user base.
 * 
 * @author John Ericksen
 *
 */

public abstract class EmailAdmin extends BrainTrainSecuredBasePage {
    
    private static final String emailRegExStr = "^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$";
    private static final RegularExpression emailRegEx = new RegularExpression(emailRegExStr);
    
    private static final String emailAliasRegExStr = "^[a-zA-Z0-9_ \\-]*[<].+[>]$";
    private static final RegularExpression emailAliasRegEx = new RegularExpression(emailAliasRegExStr);
    
    @InitialValue("getEmailMessageInitialValue()")
    public abstract String getEmailMessage();
    public abstract void setEmailMessage(String m);
    
    @InitialValue("getEmailSubjectInitialValue()")
    public abstract String getEmailSubject();
    public abstract void setEmailSubject(String s);
    
    @InitialValue("getEmailFromInitialValue()")
    public abstract String getEmailFrom();
    public abstract void setEmailFrom(String f);
    
    @InjectPage("Home")
    public abstract Home getHomePage();
    
    @Bean
    public abstract ValidationDelegate getDefaultDelegate();
    
    public String getEmailMessageInitialValue()
    {
        BrainTrainProperties message = getNonNullBrainTrainProperies(BrainTrainProperty.certificateEmailMessage.name());
        
        return message.getValue();
    }
    
    public String getEmailSubjectInitialValue()
    {
        BrainTrainProperties message = getNonNullBrainTrainProperies(BrainTrainProperty.certificateEmailSubject.name());
        
        return message.getValue();
    }
    
    public String getEmailFromInitialValue()
    {
        BrainTrainProperties message = getNonNullBrainTrainProperies(BrainTrainProperty.certificateEmailFrom.name());
        
        return message.getValue();
    }
    
    public BrainTrainProperties getNonNullBrainTrainProperies(String name)
    {
        BrainTrainProperties prop = getGenericService().findUnique(SimpleSearch.simpleObjectSearch(BrainTrainProperties.class, "name", name));
        if(prop == null)
        {
            prop = new BrainTrainProperties();
            prop.setName(name);
        }
        return prop;
    }
    
    public void updateBrainTrainProperties(String name, String value)
    {
        BrainTrainProperties prop = getNonNullBrainTrainProperies(name);
        
        if(value.length() > 4000)
        {
            prop.setValue(value.substring(0, 4000));
        }
        else
        {
            prop.setValue(value);
        }
        
        getGenericService().saveOrUpdate(prop);
    }
    
    public void saveSubmit(IRequestCycle cycle)
    {
        if(validate())
        {
            updateBrainTrainProperties(BrainTrainProperty.certificateEmailMessage.name(), getEmailMessage());
            updateBrainTrainProperties(BrainTrainProperty.certificateEmailFrom.name(), getEmailFrom());
            updateBrainTrainProperties(BrainTrainProperty.certificateEmailSubject.name(), getEmailSubject());
            
            cycle.activate(getHomePage());
        }
        //todo:redirect
    }
    
    public void cancelSubmit(IRequestCycle cycle)
    {
        cycle.activate(getHomePage());
        //todo:redirect
    }
    
    public boolean validate()
    {
        boolean valid = true;
        String email = getEmailFrom();
        
        if(emailAliasRegEx.matches(email))
        {
            email = email.substring(email.indexOf('<')+1, email.lastIndexOf('>'));
        }
        
        if(!emailRegEx.matches(email))
        {
            getDefaultDelegate().record((IFormComponent)getComponent("fromTextBox"), "'From' email address must be valid single email address.");
            valid = false;
        }
        
        return valid;
    }
}
